package com.central.apps.handler.MaterialInventory;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.app.common.util.BLuntil;
import com.central.apps.service.IInventoryService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**入库单
 * Created by Administrator on 2022/8/23.
 */
@Slf4j
@Component
public class InstorageNewHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private IInventoryService iInventoryService;

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if (flowNode.getId().equals("approval")) {
            //审核通过后增加库存
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag) {
                //查询接收入库主表gq_instorage
                List<Map<String, Object>> list3 = handlerService.findBySql("select * from gq_instorage where id=" + id);
                String instonum = BLuntil.getParameter(list3.get(0), "instonum");//入库单号
                String instodesc = BLuntil.getParameter(list3.get(0), "instodesc");//入库描述
                String receiptnum = BLuntil.getParameter(list3.get(0), "receiptnum");//接收单号
                 String storenum = BLuntil.getParameter(list3.get(0), "warehousenum");//仓库编码
               String storedesc = BLuntil.getParameter(list3.get(0), "storedesc");//仓库描述
                String ponum = BLuntil.getParameter(list3.get(0), "ponum");//采购单号
                String recipient = BLuntil.getParameter(list3.get(0), "recipient");//
                String orgcode = BLuntil.getParameter(list3.get(0), "orgcode");//总公司编码
               // String sitecode = BLuntil.getParameter(list3.get(0), "sitecode");//分公司编码
                String deptcode = BLuntil.getParameter(list3.get(0), "deptcode");//部门编码
                String issuetype = BLuntil.getParameter(list3.get(0), "type");//入库类型，接收或者退货  receiptscomplete
                //查询采购表，获取采购信息gq_po
                List<Map<String, Object>> poList = handlerService.findBySql("select * from gq_po where ponum='" + ponum + "'");
                String billtoattn = (String) poList.get(0).get("billtoattn");//接收员
                //String projectnum = (String) poList.get(0).get("projectnum");//项目编号

                //查询入库物料详细信息表gq_instoline
                List<Map<String, Object>> list4 = handlerService.findBySql("select * from gq_instoline where instonum= '" + instonum + "'");
                if (CollectionUtils.isNotEmpty(list4)) {
                    for (Map<String, Object> objectMap : list4) {
                        String itemnum = (String) objectMap.get("itemnum");//物料编码
                        String itemdesc = (String) objectMap.get("itemdesc");//物资描述
                        int innum = (int) objectMap.get("innum");//入库数量
                        String binnum = (String) objectMap.get("binnum");//库位编号
                        String batchnum = (String) objectMap.get("batchnum");//批次编号
                        float price = (float) objectMap.get("unitcost");//单位成本
                        String unit = (String) objectMap.get("unit");//计量单位;
                        String model = (String) objectMap.get("model");//规格型号;
                        float linecost = (float) objectMap.get("linecost");//行成本
                        int matusetransid = (int) objectMap.get("matusetransid");//交易信息表主键id
                        //类型不从这里取值了，直接从主表中取值
                        //String issuetype = (String) objectMap.get("issuetype");//入库类型，接收或者退货  receiptscomplete
                        String receiptscomplete = (String) objectMap.get("receiptscomplete");//接收完成
                        //判读是否有批次编号，如果有，加入到查询条件中
                        String sqllotnum = "";
                        if (batchnum != null && !"".equals(batchnum)) {
                            sqllotnum = " and batchnum ='" + batchnum + "'";
                        }
                        String where = "itemnum  ='" + itemnum + "'and storenum ='" + storenum + "'and binnum='" + binnum + "'" + sqllotnum;
                        //不包括库位
                        String where2 = "itemnum  ='" + itemnum + "'and storenum ='" + storenum + "'" + sqllotnum;


                        //1 更新平均价格
                       // updateIncost(where2, storenum, itemnum, innum, price, issuetype, orgcode, deptcode, batchnum);

                        /* 2更新库存和库存余量表*/
                        //库存
                        Map<String, Object> mapTory = new HashMap<>();
                        mapTory.put("orgcode", orgcode);

                        mapTory.put("deptcode", deptcode);
                        mapTory.put("itemnum", itemnum);//物料编码
                        mapTory.put("itemdesc", itemdesc);//物料名称
                        mapTory.put("storenum", storenum);//仓库编号
                        mapTory.put("storedesc", storedesc);//仓库名称
                        mapTory.put("avblbalance", innum);//可用余量
                        mapTory.put("curbaltotal", innum);//库存余量
                        mapTory.put("innum", innum);//入库数量
                        mapTory.put("unit", unit);//计量单位
                        mapTory.put("model", model);//规格型号
                        //库存余量
                        // 插入库存余量
                        Map<String, Object> mapBal = new HashMap<>();
                        mapBal.put("orgcode", orgcode);
                      //  mapBal.put("sitecode", sitecode);
                        mapBal.put("deptcode", deptcode);
                        mapBal.put("binnum", binnum);//库位编号
                        mapBal.put("curbal", innum);//当前余量
                        mapBal.put("storenum", storenum);//仓库编号
                        mapBal.put("itemnum", itemnum);//物料编号
                        mapBal.put("itemdesc", itemdesc);//物料名称
                        mapBal.put("batchnum", batchnum);//批次编号
                        mapBal.put("unitcost", price);//单位成本
                        mapBal.put("avblbalance", innum);//可用余量
                        updateInvbalances(where, innum, issuetype, itemnum, storenum, mapBal, mapTory);
                        /*
                        3 接收收据写下入到库存交易表中
                        * 物料编号、物料描述、交易类型（发放）、数量、单位、交易时间（创建时间）、交易处理人（创建人）
                        * */
                        Map<String, Object> map = new HashMap<>();
                        map.put("orgcode", orgcode);
                       // map.put("sitecode", sitecode);
                        map.put("deptcode", deptcode);
                        map.put("itemnum", itemnum);//物料编号
                        map.put("itemdesc", itemdesc);//物料名称
                        map.put("type", issuetype);//类型 接收或者退货
                        map.put("quantity", innum);//数量
                        map.put("retreatnum", innum);//可退货数量
                        map.put("unit", unit);//计量单位
                        map.put("model", model);//规格型号
                        map.put("linecost", linecost);//行成本
                        map.put("storenum", storenum);//库房位置 仓库编号
                        map.put("lotnum", batchnum);//批次
                        map.put("unitcost", price);//成本
                        map.put("binnum", binnum);//库位编号
                        map.put("storedesc", storedesc);//仓库描述
                        map.put("issueto", billtoattn);//接收人
                        map.put("ponum", ponum);//采购订单
                        map.put("transdate", new Date());
                        handlerService.insert("gq_matusetrans", map);
                        //如果是退货，更新交易表信息中的可退货数量
                        if("退货".equals(issuetype)){
                            String upd = "update gq_matusetrans set retreatnum = retreatnum-"+innum+"  where id = "+matusetransid;
                            handlerService.updateBySql(upd);
                        }
                        //4更新采购订单物料详情数量
                        updatePoline(itemnum, ponum, issuetype, innum, price,receiptscomplete);
                    }
                }
            }
        }
    }

    //更新库存和库存余量表数据
    private void updateInvbalances(String where, int innum, String issType, String itemnum, String storenum, Map<String, Object> mapBal, Map<String, Object> mapTory) throws Exception {
//2更新可用数量和库存余量
        //查询库存主表，获取库存余量表 库                      存余量表这条数据查询，
        String sql2 = "select * from gq_invbalances where " + where;
        List<Map<String, Object>> list2 = handlerService.findBySql(sql2);
        if (CollectionUtils.isNotEmpty(list2)) {
            //更新库存余量表
            int curbal = (int) list2.get(0).get("curbal");//当前余量
            int avblbalance = (int) list2.get(0).get("avblbalance");//可用余量
            if ("接收".equals(issType)) {
                curbal = curbal + innum;
                avblbalance = avblbalance + innum;
            } else {
                curbal = curbal - innum;
                avblbalance = avblbalance - innum;
            }
            String upd2 = "update gq_invbalances set curbal = '" + curbal + "',avblbalance = '" + avblbalance + "' where " + where;
            handlerService.updateBySql(upd2);
        } else {
            //新增库存余量表信息
            handlerService.insert("gq_invbalances", mapBal);
        }
        //查询库存主表信息
        String sql = "select * from gq_inventory where  itemnum  ='" + itemnum + "'and storenum ='" + storenum + "'";
        List<Map<String, Object>> list = handlerService.findBySql(sql);
        if (CollectionUtils.isNotEmpty(list)) {
            String sql3 = "select * from gq_invbalances where  itemnum  ='" + itemnum + "'and storenum ='" + storenum + "'";
            //Integer warehousingty = (Integer) objectMap.get("warehousingty");//入库数量
            List<Map<String, Object>> list3 = handlerService.findBySql(sql3);
            int curbal = 0;//库存余量
            int avblbalance = 0;//可用余量
            if (CollectionUtils.isNotEmpty(list3)) {
                for (Map<String, Object> objectMap : list3) {
                    curbal = curbal+(int) objectMap.get("curbal");//库存余量
                    avblbalance = avblbalance+(int) objectMap.get("avblbalance");//库存可用余量
                }
                handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal + ", avblbalance = " + avblbalance +  " where storenum = '" + storenum + "' and itemnum = '" + itemnum + "'");
            }
            //直接调用大超的接口
            //iInventoryService.calInvQuantity(storenum, itemnum);
        } else {
            // 插入库存
            handlerService.insert("gq_inventory", mapTory);
        }
    }

//    //更新平均价格数据gq_invcost
   private void updateIncost(String where2, String storenum, String itemnum, int innum, float price, String isstype, String orgcode, String sitecode, String deptcode, String batchnum) throws Exception {
//        String sqllotnum = "";
//        if (batchnum != null && !"".equals(batchnum)) {
//            sqllotnum = " and batchnum ='" + batchnum + "'";
//        }
//        String where = "itemnum  ='" + itemnum + "'and storenum ='" + storenum + "'and binnum='" + binnum + "'" + sqllotnum;
//        //不包括库位
//        String where2 = "itemnum  ='" + itemnum + "'and storenum ='" + storenum + "'" + sqllotnum;
//
//
//        //1 更新平均价格
//        // updateIncost(where2, storenum, itemnum, innum, price, issuetype, orgcode, deptcode, batchnum);
        //物料信息表
        String sql3 = "select * from gq_item where itemnum  ='" + itemnum + "'";
        List<Map<String, Object>> list3 = handlerService.findBySql(sql3);
        float stdcost =(float) list3.get(0).get("standardcost");
        //1更新库存成本表中的上次接收成本 gq_invcost   lastcost上次接收成本字段
        //库存成本表，物料编号，库房编号，批次来进行查询更新 ,如果没值，进行新增操作
        List<Map<String, Object>> list1 = handlerService.findBySql("select avgcost from gq_invcost where " + where2);
        if (CollectionUtils.isNotEmpty(list1)) {
            //查询对应的库存余量表，获取余量，查询条件不带库位
            String sqlinvbalances = "select * from gq_invbalances where " + where2;
            List<Map<String, Object>> listInv = handlerService.findBySql(sqlinvbalances);
            if (CollectionUtils.isNotEmpty(listInv)) {
                int zong = 0;
                float avg = 0;
                float avgcost = 0;
                for (Map<String, Object> map : listInv) {
                    zong = zong + (int) map.get("curbal");
                }
                avg = (float) list1.get(0).get("avgcost");//库存平均价
                if ("接收".equals(isstype)) {
                    avgcost = (innum * price + zong * avg) / (innum + zong);//总的平均价格
                } else {
                    avgcost = (zong * avg - innum * price) / (zong - innum);//总的平均价格
                }

                String updware = "update gq_invcost set avgcost= '" + avgcost + "',lastcost = '" + price + "' where " + where2;
                handlerService.updateBySql(updware);
            }
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("orgcode", orgcode);
            map.put("sitecode", sitecode);
            map.put("deptcode", deptcode);
            map.put("storenum", storenum);
            map.put("itemnum", itemnum);
            map.put("batchnum", batchnum);
            map.put("avgcost", price);
            map.put("newavgcost", price);
            map.put("stdcost", stdcost);
            handlerService.insert("gq_invcost", map);
        }
    }

    //更新采购明细数据gq_poline
    private void updatePoline(String itemnum, String ponum, String issuetype, int innum, float price,String receiptscomplete) {
        //3.更新采购明细数据poline
        String sql1 = "select * from gq_poline where itemnum  ='" + itemnum + "'and ponum ='" + ponum + "'";
        List<Map<String, Object>> list5 = handlerService.findBySql(sql1);
        float receivedlinecost = 0;//已接收行成本不含税
        int receivedqty = 0;//已接收数
        int amounttoreceive = 0;//待接收数
        float receivedtotalcost = 0;//已接收行成本（含税）

        if ("接收".equals(issuetype)) {
            receivedlinecost = (float) list5.get(0).get("receivedlinecost") + (innum * price);//;//已接收行成本（不含税）
            receivedqty = (Integer) list5.get(0).get("receivedqty") + innum;//已接收数+入库数
            //待接收数 amounttoreceive
            amounttoreceive = (Integer) list5.get(0).get("amounttoreceive") - innum;//待接收数-入库数
            receivedtotalcost = (float) list5.get(0).get("receivedtotalcost") + (innum * price);//已接收行成本（含税）
        } else {
            receivedlinecost = (float) list5.get(0).get("receivedlinecost") - (innum * price);//;//已接收行成本（不含税）
            receivedqty = (Integer) list5.get(0).get("receivedqty") - innum;//已接收数-入库数
            //待接收数 amounttoreceive
            amounttoreceive = (Integer) list5.get(0).get("amounttoreceive") + innum;//待接收数+入库数
            receivedtotalcost = (float) list5.get(0).get("receivedtotalcost") - (innum * price);//已接收行成本（含税）
        }

        String updpoline = "update gq_poline set amounttoreceive='" + amounttoreceive + "',receivedlinecost='" + receivedlinecost
                + "',receivedtotalcost='" + receivedtotalcost
                + "',receivedqty='" + receivedqty + "',receiptscomplete='"+receiptscomplete+"' where itemnum  ='" + itemnum + "'and ponum ='" + ponum + "'";

        handlerService.updateBySql(updpoline);

    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_instoline".equals(objName)){
            Integer amounttoreceive = MapUtils.getInteger(data, "amounttoreceive");//待接收的数量
            Integer innum = MapUtils.getInteger(data, "innum");//入库数量
            String itemnum = MapUtils.getString(data, "itemnum");//物料编码
            String instonum = MapUtils.getString(data, "instonum");//入库单号
            String receiptscomplete = MapUtils.getString(data, "receiptscomplete");//是否接受
            List<Map<String, Object>> bySql = handlerService.findBySql("select tolerancequantity,tolerance from gq_item where itemnum = '" + itemnum + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    Integer tolerancequantity = MapUtils.getInteger(map, "tolerancequantity");//允差数量(±)
                    Integer tolerance = MapUtils.getInteger(map, "tolerance");
                    tolerance  = (tolerance == null ? 0 : tolerance);
                    if (tolerance==0&&(amounttoreceive-innum)==0){
                        receiptscomplete="1";
                        handlerService.updateBySql("update gq_instoline set receiptscomplete ='"+receiptscomplete+"' where  itemnum='"+itemnum+"' and instonum ='"+instonum+"'");
                    }else if (tolerance==0&&(amounttoreceive-innum)!=0){
                        receiptscomplete="0";
                        handlerService.updateBySql("update gq_instoline set receiptscomplete ='"+receiptscomplete+"' where  itemnum='"+itemnum+"' and instonum ='"+instonum+"'");
                    }else if (tolerance!=0&&(amounttoreceive-innum)<=tolerancequantity){
                        receiptscomplete="1";
                        handlerService.updateBySql("update  gq_instoline set receiptscomplete ='"+receiptscomplete+"' where  itemnum='"+itemnum+"' and instonum ='"+instonum+"'");
                    }else if (tolerance!=0&&(amounttoreceive-innum)>tolerancequantity){
                        receiptscomplete="0";
                        handlerService.updateBySql("update gq_instoline set receiptscomplete ='"+receiptscomplete+"' where  itemnum='"+itemnum+"' and instonum ='"+instonum+"'");
                    }

                }
            }

        }
        super.afterSave(app, objName, data, isUpdate);
    }

//    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//
//        if ("gq_instorageaa".equals(objName)) {
//            String ponum = MapUtils.getString(data, "ponum");// 采购订单号
//            String instonum = MapUtils.getString(data, "instonum");// 入库单号
//
//            String sql = "select * from gq_poline where ponum = '" + ponum + "'";
//            List<Map<String, Object>> datas = new ArrayList<>();
//            List<Map<String, Object>> list = handlerService.findBySql(sql);
//            if (CollectionUtils.isNotEmpty(list)) {
//                for (Map<String, Object> map : list) {
//                    Map<String, Object> insertMap = new HashMap<>();
//                    insertMap.put("instonum", instonum);// 入库单号
//                    insertMap.put("ponum", ponum);// 采购订单号
//                    insertMap.put("polinenum", map.get("polinenum"));// 行号
//                    insertMap.put("linetype", map.get("linetype"));// 行类型
//                    insertMap.put("itemnum", map.get("itemnum"));// 物料编码
//                    insertMap.put("itemdesc", map.get("itemdesc"));// 物料名称
//                    insertMap.put("model", map.get("modelnum"));// 型号
//                    insertMap.put("unit", map.get("orderunit"));// 计量单位
//                    insertMap.put("unitcost", map.get("unitcost"));// 单位成本
//                    insertMap.put("tax1code", map.get("tax1code"));// 行成本
//                    insertMap.put("tax", map.get("tax"));// 行号
//                    insertMap.put("tax1", map.get("tax1"));// 行号
//                    insertMap.put("beforetax", map.get("beforetax"));// 行号
//                    insertMap.put("amounttoreceive", map.get("amounttoreceive"));// 行号
//                    insertMap.put("receivedlinecost", map.get("receivedlinecost"));// 行号
//                    insertMap.put("receivedqty", map.get("receivedqty"));// 行号
//                    insertMap.put("receivedunitcost", map.get("receivedunitcost"));// 行号
//                    insertMap.put("receivedtotalcost", map.get("receivedtotalcost"));// 行号
//                    insertMap.put("receiptscomplete", map.get("receiptscomplete"));// 行号
//                    insertMap.put("rejectedqty", map.get("rejectedqty"));// 行号
//                    insertMap.put("inspectreceive", map.get("inspectreceive"));// 行号
//                    insertMap.put("inspectqty", map.get("inspectqty"));// 行号
//                    insertMap.put("requestedby", map.get("requestedby"));// 行号
//                    insertMap.put("reqdeliverydate", map.get("reqdeliverydate"));// 行号
//                    insertMap.put("manufacturer", map.get("manufacturer"));// 行号
//                    insertMap.put("contractnum", map.get("contractnum"));// 行号
//                    insertMap.put("contractid", map.get("contractid"));// 行号
//                    insertMap.put("contractlineid", map.get("contractlineid"));// 行号insertMap.put("contractnum", map.get("contractnum"));// 行号
//                    insertMap.put("contractlinenum", map.get("contractlinenum"));// 行号
//                    insertMap.put("shipto", map.get("shipto"));// 行号
//                    insertMap.put("billto", map.get("billto"));// 行号
//                    insertMap.put("shiptoattn", map.get("shiptoattn"));// 行号
//                    insertMap.put("rfqnum", map.get("rfqnum"));// 行号
//                    insertMap.put("rfqlinenum", map.get("rfqlinenum"));// 询价单行号
//                    insertMap.put("psnum", map.get("psnum"));// 验收单号
//                    insertMap.put("projectnum", map.get("projectnum"));// 项目编号
//
//                    datas.add(insertMap);
//                }
//                //先批量删除在插入
//                String del = "delete from gq_instoline where instonum = '" + instonum + "'";
//                handlerService.updateBySql(del);
//                //插入到接收入库的采购订单明细表
//                handlerService.batchInsert("instorageApp", "gq_instoline", datas);
//            }
//        }
//        /*
//        * 新库存余量，是不是 旧库存余量加上入库数量
//        * 可用数量  是不是 旧的可用数量加上入库数量
//        *
//        * 待接收数量和入库数量是什么关系
//        * */
//        //1更新可用数量和库存余量
//        if ("gq_instolineqq".equals(objName)) {
//            String itemnum = MapUtils.getString(data, "itemnum");
//            //查询库存主表，获取库存余量表
//            String sql = "select * from gq_inventory where  itemnum  = '" + itemnum + "'";
//            Integer amounttoreceive = MapUtils.getInteger(data, "amounttoreceive");//待接收数量
//            List<Map<String, Object>> list = handlerService.findBySql(sql);
//            Integer curbaltotal = 0;//库存余量
//            if (CollectionUtils.isNotEmpty(list)) {
//                curbaltotal = (Integer) list.get(0).get("curbaltotal");//库存余量
//                Integer avblbalance = (Integer) list.get(0).get("avblbalance");//可用余量
//                curbaltotal = curbaltotal + amounttoreceive;
//                avblbalance = avblbalance + amounttoreceive;
//                String upd = "update gq_inventory set curbaltotal= '" + curbaltotal + "',avblbalance='" + avblbalance + "' where itemnum  ='" + itemnum + "'";
//                handlerService.updateBySql(upd);
//            }
//
//
//            Integer innum = MapUtils.getInteger(data, "innum");//入库数量
//            /*
//            * 问题一，入库价格从哪里获取
//            * 问题二，税前价格 是否是入库价格   入库单价字段：price
//            * */
//            //2更新库存成本表中的上次接收成本 gq_invcost   lastcost上次接收成本字段
//            List<Map<String, Object>> list1 = handlerService.findBySql("select avgcost from gq_invcost where itemnum= '" + itemnum + "'");
//            if (CollectionUtils.isNotEmpty(list1)) {
//                Integer zong = curbaltotal;//暂时把库存余量 当成库存总量
//                float price = MapUtils.getFloat(data, "price");
//                ;//入库价格
//                float avg = (float) list1.get(0).get("avgcost");//库存平均价 从库存台账表中获取
//                float avgcost = (innum * price + zong * avg) / (innum + zong);//总的平均价格
//                String updware = "update gq_invcost set avgcost= '" + avgcost + "' ,lastcost = '" + price + "' where itemnum='" + itemnum + "'";
//                handlerService.updateBySql(updware);
//            }
//
//            //Integer warehousingty =
//            //3 接收收据写下入到库存交易表中
//            String itemdesc = MapUtils.getString(data, "itemdesc");
//            //String warehousingty = MapUtils.getString(data, "warehousingty");//入库数量
//            String unit = MapUtils.getString(data, "unit");
//            LoginAppUser user = SysUserUtil.getLoginAppUser();
//            /*
//            * 物料编号、物料描述、交易类型（发放）、数量、单位、交易时间（创建时间）、交易处理人（创建人）
//            * */
//            Map<String, Object> map = new HashMap<>();
//            map.put("itemnum", itemnum);
//            map.put("itemdesc", itemdesc);
//            map.put("issuetype", "发放");
//            map.put("quantity", innum);
//            map.put("unit", unit);
//            map.put("issueto", user.getUsername());
//            map.put("transdate", new Date());
//            handlerService.insert("gq_matusetrans", map);
//
//
//            //4.更新采购明细数据poline
//            float receivedlinecost = MapUtils.getFloat(data, "receivedlinecost");//已接收行成本（不含税）
//            Integer receivedqty = MapUtils.getInteger(data, "receivedqty");
//            ;//已接收数量
//            float receivedunitcost = MapUtils.getFloat(data, "receivedunitcost");//已接收成本
//            float receivedtotalcost = MapUtils.getFloat(data, "receivedtotalcost");//已接收行成本
//            String updpoline = "update gq_poline set amounttoreceive='" + amounttoreceive + "',receivedlinecost='" + receivedlinecost
//                    + "',receivedunitcost='" + receivedunitcost + "',receivedtotalcost='" + receivedtotalcost
//                    + "',receivedqty='" + receivedqty + "' where itemnum='" + itemnum + "'";
//
//            handlerService.updateBySql(updpoline);
//        }


//    }

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {

        /*
        * 问题一：订购数量从哪里获取,是否从采购订单中获取
        * 问题二：待接收数量怎么理解
        * */

        //允差校验
        if ("gq_instoline".equals(objName)) {
            String instonum = MapUtils.getString(data, "instonum");//接收入库主表编号，用于查询类型
            List<Map<String, Object>> list3 = handlerService.findBySql("select * from gq_instorage where instonum='" + instonum+"'");
            String issuetype =(String)list3.get(0).get("type");// MapUtils.getString(data, "issuetype");//类型
            String ponum = MapUtils.getString(data, "ponum");//采购订单号
            String itemnum = MapUtils.getString(data, "itemnum");//物料编号
            //String issuetype = MapUtils.getString(data, "issuetype");//类型
            int receiptscomplete = MapUtils.getInteger(data, "receiptscomplete");//接收完成
            //待接收数量
            Integer amounttoreceive = MapUtils.getInteger(data, "amounttoreceive");
            //已接收数量
            Integer receivedqty = MapUtils.getInteger(data, "receivedqty");
            //如果点击接收完成，需要进行校验，包含允差计算
            if (receiptscomplete == 1) {
                //采购订单明细信息表
                String sql = "select * from gq_poline where ponum = '" + ponum + "' and itemnum  ='" + itemnum + "'";
                List<Map<String, Object>> list = handlerService.findBySql(sql);
                //物料信息表
                String sql1 = "select * from gq_item where itemnum  ='" + itemnum + "'";
                List<Map<String, Object>> list1 = handlerService.findBySql(sql1);
                int tolerancequantity = 0;//允差数量默认为0
                int orderqty = 0;//订购数量
                if (CollectionUtils.isNotEmpty(list) && CollectionUtils.isNotEmpty(list1)) {
                    Integer tolerance = (Integer) list1.get(0).get("tolerance");//是否允差
                    if (tolerance == 1) {
                        tolerancequantity = (Integer) list1.get(0).get("tolerancequantity");//允差数量
                        orderqty = (Integer) list.get(0).get("orderqty");//订购数量
                    }
                }

                //如果订单数量小于 待接收数量加允差值，则提示不能接收完成
                if (orderqty > (amounttoreceive + tolerancequantity)) {
                    String result = "待接收数量不足，不允许勾选接收完成";
                    return result;
                }
            }
            //获取入库数量
            if("接收".equals(issuetype)){
                Integer innum = MapUtils.getInteger(data, "innum");
                if (innum > amounttoreceive) {
                    String result = "入库数量不能大于待接收数量";
                    return result;
                }
            }else {
                Integer innum = MapUtils.getInteger(data, "innum");
                if (innum > receivedqty) {
                    String result = "退货数量不能大于待接收数量";
                    return result;
                }
            }

        }
        return super.validateSave(app, objName, data);
    }
}
